package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TPayChannel;
import com.ruoyi.business.enums.OrderInfoExceptionEnum;
import com.ruoyi.business.enums.OrderStatus;
import com.ruoyi.business.mapper.TOrderInfoMapper;
import com.ruoyi.business.response.ErrorResponseData;
import com.ruoyi.business.response.OrderStatisticResp;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.response.SuccessResponseData;
import com.ruoyi.business.service.ITOrderInfoService;
import com.ruoyi.business.service.ITPayChannelService;
import com.ruoyi.business.service.PaymentInterface;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.GlobalConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServerExceptionEnum;
import com.ruoyi.common.utils.AesEncryptUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单列表Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-02-26
 */
@Service
public class TOrderInfoServiceImpl implements ITOrderInfoService
{
    @Autowired
    private TOrderInfoMapper tOrderInfoMapper;


    @Resource
    private ITPayChannelService payChannelService;



    private static final Logger logger = LoggerFactory.getLogger(TOrderInfoServiceImpl.class);
    @Autowired
    private ISysConfigService sysConfigService;


    /**
     * 查询订单列表
     * 
     * @param id 订单列表主键
     * @return 订单列表
     */
    @Override
    public TOrderInfo selectTOrderInfoById(Long id)
    {
        return tOrderInfoMapper.selectTOrderInfoById(id);
    }

    @Override
    @DataScope(userAlias = "t")
    public List<TOrderInfo> selectTOrderInfoListBySh(TOrderInfo tOrderInfo) {
        return tOrderInfoMapper.selectTOrderInfoList(tOrderInfo);
    }

    /**
     * 查询订单列表列表
     * 
     * @param tOrderInfo 订单列表
     * @return 订单列表
     */
    @Override
    @DataScope(permission = "t")
    public List<TOrderInfo> selectTOrderInfoList(TOrderInfo tOrderInfo)
    {
        return tOrderInfoMapper.selectTOrderInfoList(tOrderInfo);
    }

    @Override
    public List<TOrderInfo> selectTOrderInfoListByNoAuth(TOrderInfo tOrderInfo) {
        return tOrderInfoMapper.selectTOrderInfoListByNoAuth(tOrderInfo);

    }

    /**
     * 新增订单列表
     * 
     * @param tOrderInfo 订单列表
     * @return 结果
     */
    @Override
    public int insertTOrderInfo(TOrderInfo tOrderInfo)
    {
        tOrderInfo.setCreateTime(DateUtils.getNowDate());
        return tOrderInfoMapper.insertTOrderInfo(tOrderInfo);
    }

    /**
     * 修改订单列表
     * 
     * @param tOrderInfo 订单列表
     * @return 结果
     */
    @Override
    public int updateTOrderInfo(TOrderInfo tOrderInfo)
    {
        tOrderInfo.setUpdateTime(DateUtils.getNowDate());
        return tOrderInfoMapper.updateTOrderInfo(tOrderInfo);
    }

    /**
     * 批量删除订单列表
     * 
     * @param ids 需要删除的订单列表主键
     * @return 结果
     */
    @Override
    public int deleteTOrderInfoByIds(String ids)
    {
        return tOrderInfoMapper.deleteTOrderInfoByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除订单列表信息
     * 
     * @param id 订单列表主键
     * @return 结果
     */
    @Override
    public int deleteTOrderInfoById(Long id)
    {
        return tOrderInfoMapper.deleteTOrderInfoById(id);
    }

    @Override
    public ResponseData addNewOrder(TOrderInfo orderInfo) throws Exception {
        String nginxPayGateway = sysConfigService.selectConfigByKey("sys.bussine.nginxPayGateway");
        Map<String, String> map = new HashMap<>();
        map.put("c", orderInfo.getChannel());
        map.put("o", orderInfo.getId().toString());
        // 明文参数
        String p = JSONObject.toJSONString(map);
        // 密文参数
        String pp = AesEncryptUtils.encrypt(p);
        TPayChannel payChannel = payChannelService.selectTPayChannelByCode(orderInfo.getChannel());
        String payUrl = nginxPayGateway + GlobalConstants.API_BASE_URL + "payment/"+payChannel.getAliasName().toLowerCase() + "?p=" + pp;
        orderInfo.setPayUrl(payUrl);
        PaymentInterface paymentInterface;
        try {
            paymentInterface = (PaymentInterface) SpringUtils.getBean(payChannel.getAliasName().toLowerCase() + "PayService");
        } catch (BeansException e) {
            logger.info("支付渠道类型[channel=" + payChannel.getChannel() + "]实例化异常");
            return new ErrorResponseData(ServerExceptionEnum.CHANNEL_ERROR.getCode(),ServerExceptionEnum.CHANNEL_ERROR.getMessage()+"，原因：支付渠道类型[channel=" + payChannel.getChannel() + "]实例化异常");
        }
        JSONObject payResultObj = paymentInterface.createPayOrder(orderInfo);
        if (payResultObj.getString("code").equals("200")) {
            orderInfo.setStatus(OrderStatus.WAIT_PAY.getCode());
            orderInfo.setQrcodeUrl(payResultObj.getString("payUrl"));
            orderInfo.setPay3rdOrderNo(payResultObj.getString("orderNo"));
            logger.info("更新后的订单三方id:{},收款账号：{}，收款账号id:{}", orderInfo.getPay3rdOrderNo(), orderInfo.getChannelAccount(), orderInfo.getRecipientId());
        } else {
            logger.error("生成订单失败：原因：{}", payResultObj.getString("msg"));
            return new ErrorResponseData(OrderInfoExceptionEnum.CREATE_FAIL.getCode(),OrderInfoExceptionEnum.CREATE_FAIL.getMessage()+"，原因："+payResultObj.getString("msg"));
        }
        //根据不同编码调用不同通道
//        if (orderInfo.getChannel().equalsIgnoreCase("alipay_yxe_h5")) {//银小二
//            JSONObject yxeObj = yxePayService.createPayOrder(orderInfo);
//            if (yxeObj.getString("code").equals("200")) {
//                orderInfo.setStatus(OrderStatus.WAIT_PAY.getCode());
//                logger.info("更新后的订单三方id:{},收款账号：{}，收款账号id:{}", orderInfo.getPay3rdOrderNo(), orderInfo.getChannelAccount(), orderInfo.getRecipientId());
//            } else {
//                logger.error("生成订单失败：原因：{}", yxeObj.getString("msg"));
//                throw new ServiceException(OrderInfoExceptionEnum.CREATE_FAIL.getMessage());
//            }
//        } else if (orderInfo.getChannel().equalsIgnoreCase("alipay_cxzf_h5")) {//诚享支付
//            JSONObject cxObj = cxzfPayService.createPayOrder(orderInfo);
//            if (cxObj.getString("code").equals("200")) {
//                orderInfo.setQrcodeUrl(cxObj.getString("payUrl"));
//                orderInfo.setPay3rdOrderNo(cxObj.getString("orderNo"));
//                orderInfo.setStatus(OrderStatus.WAIT_PAY.getCode());
//                logger.info("更新后的订单三方id:{},收款账号：{}，收款账号id:{}", orderInfo.getPay3rdOrderNo(), orderInfo.getChannelAccount(), orderInfo.getRecipientId());
//            } else {
//                logger.error("生成订单失败：原因：{}", cxObj.getString("msg"));
//                throw new ServiceException(OrderInfoExceptionEnum.CREATE_FAIL.getMessage());
//            }
//        } else if (orderInfo.getChannel().equalsIgnoreCase("alipay_hdf_h5")) {//好多分
//            JSONObject hdfObj = hdfPayService.createPayOrder(orderInfo);
//            if (hdfObj.getString("code").equals("200")) {
//                orderInfo.setQrcodeUrl(hdfObj.getString("payUrl"));
//                orderInfo.setPay3rdOrderNo(hdfObj.getString("orderNo"));
//                orderInfo.setStatus(OrderStatus.WAIT_PAY.getCode());
//                logger.info("更新后的订单三方id:{},收款账号：{}，收款账号id:{}", orderInfo.getPay3rdOrderNo(), orderInfo.getChannelAccount(), orderInfo.getRecipientId());
//            } else {
//                logger.error("生成订单失败：原因：{}", hdfObj.getString("msg"));
//                throw new ServiceException(OrderInfoExceptionEnum.CREATE_FAIL.getMessage());
//            }
//        }else if (orderInfo.getChannel().equalsIgnoreCase("alipay_wl_h5")) {//好多分
//            JSONObject wlObj = wlPayService.createPayOrder(orderInfo);
//            if (wlObj.getString("code").equals("200")) {
//                orderInfo.setQrcodeUrl(wlObj.getString("payUrl"));
//                orderInfo.setStatus(OrderStatus.WAIT_PAY.getCode());
//                logger.info("更新后的订单三方id:{},收款账号：{}，收款账号id:{}", orderInfo.getPay3rdOrderNo(), orderInfo.getChannelAccount(), orderInfo.getRecipientId());
//            } else {
//                logger.error("生成订单失败：原因：{}", wlObj.getString("msg"));
//                throw new ServiceException(OrderInfoExceptionEnum.CREATE_FAIL.getMessage());
//            }
//        }if (orderInfo.getChannel().equalsIgnoreCase("alipay_syb_h5")) {
//            orderInfo.setStatus(OrderStatus.WAIT_PAY.getCode());
//        }else if (orderInfo.getChannel().equalsIgnoreCase("alipay_dy_h5")) {//好多分
//            JSONObject dyObj = douYinPayService.createPayOrder(orderInfo);
//            if (dyObj.getString("code").equals("200")) {
//                orderInfo.setQrcodeUrl(dyObj.getString("payUrl"));
//                orderInfo.setPay3rdOrderNo(dyObj.getString("orderNo"));
//                orderInfo.setStatus(OrderStatus.WAIT_PAY.getCode());
//                logger.info("更新后的订单三方id:{},收款账号：{}，收款账号id:{}", orderInfo.getPay3rdOrderNo(), orderInfo.getChannelAccount(), orderInfo.getRecipientId());
//            } else {
//                logger.error("生成订单失败：原因：{}", dyObj.getString("msg"));
//                throw new ServiceException(OrderInfoExceptionEnum.CREATE_FAIL.getMessage());
//            }
//        }else  if (orderInfo.getChannel().equalsIgnoreCase("card_to_card")) {
//            orderInfo.setQrcodeUrl(userRecipientInfo.getCardNo());
//            orderInfo.setBankName(userRecipientInfo.getBankName());
//            orderInfo.setStatus(OrderStatus.WAIT_PAY.getCode());
//        }else if (orderInfo.getChannel().equalsIgnoreCase("alipay_cez_h5")) {//好多分
//            JSONObject cezObj = cezPayService.createPayOrder(orderInfo);
//            if (cezObj.getString("code").equals("200")) {
//                orderInfo.setQrcodeUrl(cezObj.getString("payUrl"));
//                orderInfo.setPay3rdOrderNo(cezObj.getString("orderNo"));
//                orderInfo.setStatus(OrderStatus.WAIT_PAY.getCode());
//                logger.info("更新后的订单三方id:{},收款账号：{}，收款账号id:{}", orderInfo.getPay3rdOrderNo(), orderInfo.getChannelAccount(), orderInfo.getRecipientId());
//            } else {
//                logger.error("生成订单失败：原因：{}", cezObj.getString("msg"));
//                throw new ServiceException(OrderInfoExceptionEnum.CREATE_FAIL.getMessage());
//            }
//        }else if (orderInfo.getChannel().equalsIgnoreCase("alipay_eft_h5")) {//易富通
//            JSONObject cxObj = eftPayService.createPayOrder(orderInfo);
//            if (cxObj.getString("code").equals("200")) {
//                orderInfo.setQrcodeUrl(cxObj.getString("payUrl"));
//                orderInfo.setPay3rdOrderNo(cxObj.getString("orderNo"));
//                orderInfo.setStatus(OrderStatus.WAIT_PAY.getCode());
//                logger.info("更新后的订单三方id:{},收款账号：{}，收款账号id:{}", orderInfo.getPay3rdOrderNo(), orderInfo.getChannelAccount(), orderInfo.getRecipientId());
//            } else {
//                logger.error("生成订单失败：原因：{}", cxObj.getString("msg"));
//                throw new ServiceException(OrderInfoExceptionEnum.CREATE_FAIL.getMessage());
//            }
//        }else if (orderInfo.getChannel().equalsIgnoreCase("alipay_yinlian_h5")) {//易富通
//            JSONObject cxObj = aliPayYinLianService.createPayOrder(orderInfo);
//            if (cxObj.getString("code").equals("200")) {
//                orderInfo.setQrcodeUrl(cxObj.getString("payUrl"));
//                orderInfo.setStatus(OrderStatus.WAIT_PAY.getCode());
//                logger.info("更新后的订单三方id:{},收款账号：{}，收款账号id:{}", orderInfo.getQrcodeUrl(), orderInfo.getChannelAccount(), orderInfo.getRecipientId());
//            } else {
//                logger.error("生成订单失败：原因：{}", cxObj.getString("msg"));
//                throw new ServiceException(OrderInfoExceptionEnum.CREATE_FAIL.getMessage());
//            }
//        }else if (orderInfo.getChannel().equalsIgnoreCase("alipay_kmt_h5")) {//易富通
//            JSONObject kmtObj = kmtPayService.createPayOrder(orderInfo);
//            if (kmtObj.getString("code").equals("200")) {
//                orderInfo.setQrcodeUrl(kmtObj.getString("payUrl"));
//                orderInfo.setPay3rdOrderNo(kmtObj.getString("orderNo"));
//                orderInfo.setStatus(OrderStatus.WAIT_PAY.getCode());
//                logger.info("更新后的订单三方id:{},收款账号：{}，收款账号id:{}", orderInfo.getQrcodeUrl(), orderInfo.getChannelAccount(), orderInfo.getRecipientId());
//            } else {
//                logger.error("生成订单失败：原因：{}", kmtObj.getString("msg"));
//                throw new ServiceException(OrderInfoExceptionEnum.CREATE_FAIL.getMessage());
//            }
//        }else if (orderInfo.getChannel().equalsIgnoreCase("alipay_yyh_h5")) {//易云汇
//            JSONObject kmtObj = yyhPayService.createPayOrder(orderInfo);
//            if (kmtObj.getString("code").equals("200")) {
//                orderInfo.setQrcodeUrl(kmtObj.getString("payUrl"));
//                orderInfo.setPay3rdOrderNo(kmtObj.getString("orderNo"));
//                orderInfo.setStatus(OrderStatus.WAIT_PAY.getCode());
//                logger.info("更新后的订单三方id:{},收款账号：{}，收款账号id:{}", orderInfo.getQrcodeUrl(), orderInfo.getChannelAccount(), orderInfo.getRecipientId());
//            } else {
//                logger.error("生成订单失败：原因：{}", kmtObj.getString("msg"));
//                throw new ServiceException(OrderInfoExceptionEnum.CREATE_FAIL.getMessage());
//            }
//        }
        updateTOrderInfo(orderInfo);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info("===============订单生成时间:{}", dateFormat.format(orderInfo.getCreateTime()));
        return new SuccessResponseData(orderInfo);
    }

    @Override
    @DataScope(permission = "t")
    public OrderStatisticResp statistic(TOrderInfo orderInfoParam) {
        return tOrderInfoMapper.statistic(orderInfoParam);
    }

    @Override
    @DataScope(userAlias = "t")
    public OrderStatisticResp statisticBySh(TOrderInfo orderInfoParam) {
        return tOrderInfoMapper.statistic(orderInfoParam);
    }

    @Override
    @DataScope(permission = "t")
    public List<OrderStatisticResp>  statisticList(TOrderInfo orderInfoParam) {
        orderInfoParam.setQryType("ms");
        return tOrderInfoMapper.statisticList(orderInfoParam);
    }

    @Override
    @DataScope(userAlias = "t")
    public List<OrderStatisticResp>  statisticByShList(TOrderInfo orderInfoParam) {
        orderInfoParam.setQryType("sh");
        return tOrderInfoMapper.statisticList(orderInfoParam);
    }

    @Override
    public int updateAllTimeout() {
        return tOrderInfoMapper.updateAllTimeout();
    }
}
